//
//  QSCustomTabBarController.swift
//  TestSwift
//
//  Created by Song on 2018/11/7.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

class QSCustomTabBarController: UITabBarController {
    /// 数据源需要的数据
    let dataArr: Array<(title: String, titleColor: UIColor, selTitleColor: UIColor, img: String, selImg: String)> = [
        ("11111", UIColor.red, UIColor.blue, "icon_menu_news_off", "icon_menu_news_on"),
        ("22222", UIColor.red, UIColor.blue, "icon_menu_news_off", "icon_menu_news_on"),
        ("33333", UIColor.red, UIColor.blue, "icon_menu_news_off", "icon_menu_news_on"),
        ("44444", UIColor.red, UIColor.blue, "icon_menu_news_off", "icon_menu_news_on")]
    
    // 控制器
    private let vcArray = [ViewController11111(), ViewController22222(), ViewController33333(), ViewController22222()]
    
    // tintColor
    private let itemColor = UIColor.black
    private let barBgColor = UIColor.yellow
    
    override var selectedIndex: Int {
        didSet {
            (self.tabBar as! QSCustomTabBar).qs_selectItem(index: selectedIndex, isResponseDelegate: false)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用自定义的tabBar
        let newTabBar = QSCustomTabBar.init()
        newTabBar.qs_delegate = self
        newTabBar.qs_dataSource = self
        self.setValue(newTabBar, forKey: "tabBar")
        self.tabBar.isTranslucent = false
        self.tabBar.barTintColor = barBgColor
        
        guard self.dataArr.count > 0 else {
            return
        }
        
        // 设置子控制器
        self.qs_setSubViewControllers()
        // 默认选中第一个item
        self.selectedIndex = 0
    }
    
    // MARK: - Private Methods
    /// 设置子控制器
    func qs_setSubViewControllers(){
        for vc in vcArray {
            // 创建导航控制器
            let nav = UINavigationController.init(rootViewController: vc)
            self.addChildViewController(nav)
        }
    }
}

extension QSCustomTabBarController: QSCustomTabBarDelegate {
    func qs_tabBar(tabBar: QSCustomTabBar, didSelectedItemAt index: Int) {
        // 切换到对应index的viewController
        self.selectedIndex = index
    }
    
    func qs_tabBarDidSelectedCenterItem(tabBar: QSCustomTabBar) {
        print("dsfhjksfkdhf")
    }
}

extension QSCustomTabBarController: QSCustomTabBarDataSource {
    func qs_numberOfItems(in tabBar: QSCustomTabBar) -> Int {
        return self.dataArr.count
    }
    
    func qs_tabBar(_ tabBar: QSCustomTabBar, dataForItemAt index: Int) -> (title: String, titleColor: UIColor, selTitleColor: UIColor, img: String, selImg: String) {
        let data = self.dataArr[index]
        return data
    }
}
